package com.kittyhawks.bksystem.weixin.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.kittyhawks.bksystem.entity.Photographer;
import com.kittyhawks.bksystem.service.PgrInfoService;
import com.kittyhawks.bksystem.weixin.controller.Base;
import com.kittyhawks.bksystem.weixin.dto.WeiXinAuthorizeDTO;
import com.kittyhawks.bksystem.weixin.dto.WeiXinUserInfoDTO;
import com.kittyhawks.bksystem.weixin.service.WeChatAuthService;
import com.kittyhawks.bksystem.weixin.util.WeiXinFinalValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by VS on 2018/4/12.
 */
@Component
public class WeixinPhotographerInterceptor implements HandlerInterceptor {

    @Autowired
    private WeChatAuthService weiXinUserService;

    @Autowired
    private PgrInfoService pgrInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        HttpSession httpSession=request.getSession();
        Photographer userInfo=(Photographer) httpSession.getAttribute(WeiXinFinalValue.WX_SESSION_USER);
        //判断是否已登录
        if(!Base.empty(userInfo)){
            //未登录
            String agent = request.getHeader("User-Agent");

            //如果是微信客户端打开  我们才进行授权处理
            if(null!=agent&&agent.toLowerCase().indexOf("micromessenger")>=0) {
                String code=request.getParameter("code");
                String state=request.getParameter("state");
                System.out.println("code = "+code+"  state= "+state);
                if(Base.notEmpty(code)&&Base.notEmpty(state)&&state.equals("1")){
                    try {
                        //通过Code获取openid来进行授权
                        String resContent = weiXinUserService.getAccessToken(code);
                        System.out.println("【微信用户Token信息】========>>>>>>>"+resContent);
                        WeiXinAuthorizeDTO weiXinAuthorizeDTO= JSONObject.parseObject(resContent,WeiXinAuthorizeDTO.class);
                        //查到用户token 并且用户从未绑定过  则自动绑定信息
                        if(Base.notEmpty(weiXinAuthorizeDTO)&&Base.empty(userInfo.getOpenid())){
                            JSONObject jsonobject = weiXinUserService.getUserInfo(weiXinAuthorizeDTO.getAccess_token(),weiXinAuthorizeDTO.getOpenid());
                            System.out.println("【微信用户信息】========>>>>>>>"+jsonobject);
                            WeiXinUserInfoDTO weiXinUserInfoDTO = JSONObject.parseObject(jsonobject.toJSONString(),WeiXinUserInfoDTO.class);
                            userInfo.setOpenid(weiXinUserInfoDTO.getOpenid());
                            userInfo.setNickname(weiXinUserInfoDTO.getNickname());
                            userInfo.setAvatar(weiXinUserInfoDTO.getHeadimgurl());
                            pgrInfoService.updateByPrimaryKeySelective(userInfo);
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return false;
                    }
                }else{
                    String url ="welcome";//跳回登录页面
                    response.sendRedirect(url);
                    return false;
                }
                return false;
            }
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}


